package com.example.im.utils;

import android.widget.Toast;

import com.example.common.AppConfig;
import com.example.common.MyApplication;
import com.example.common.interfaces.CommonCallback;
import com.example.common.utils.L;
import com.example.common.utils.SPUtils;
import com.example.im.bean.MessageBean;
import com.example.im.bean.UserInfoBean;
import com.example.im.interfaces.ImClient;
import com.example.im.interfaces.SendMsgResultCallback;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMConversationResult;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMOfflinePushConfig;
import com.tencent.imsdk.v2.V2TIMSDKConfig;
import com.tencent.imsdk.v2.V2TIMSDKListener;
import com.tencent.imsdk.v2.V2TIMSendCallback;
import com.tencent.imsdk.v2.V2TIMSimpleMsgListener;
import com.tencent.imsdk.v2.V2TIMUserFullInfo;
import com.tencent.imsdk.v2.V2TIMUserInfo;
import com.tencent.imsdk.v2.V2TIMValueCallback;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static com.tencent.imsdk.v2.V2TIMMessage.V2TIM_ELEM_TYPE_CUSTOM;
import static com.tencent.imsdk.v2.V2TIMMessage.V2TIM_ELEM_TYPE_IMAGE;
import static com.tencent.imsdk.v2.V2TIMMessage.V2TIM_ELEM_TYPE_TEXT;


//setConversationListener更新列表监听


public class TencentImUtils implements ImClient {

    private static TencentImUtils sInstance;

    /**
     * on line
     */
    private static final int LOGIN_STATUS_ONLINE = 1;

    /**
     * off line
     */
    private static final int LOGIN_STATUS_OFFLINE = 0;
    private String TAG = this.getClass().getSimpleName();

    public TencentImUtils() {

    }

    public static TencentImUtils getInstance() {
        if (sInstance == null) {
            synchronized (TencentImUtils.class) {
                if (sInstance == null) {
                    sInstance = new TencentImUtils();
                }
            }
        }
        return sInstance;
    }

    @Override
    public void init() {
        V2TIMSDKConfig config = new V2TIMSDKConfig();
        //log输出级别
        config.setLogLevel(V2TIMSDKConfig.V2TIM_LOG_INFO);
        V2TIMManager.getInstance().initSDK(MyApplication.sInstener, AppConfig.getInstance().getMetaDataInt("TENCENT_IM_ID"), config, new V2TIMSDKListener() {
            @Override
            public void onConnecting() {
                L.e("正在连接腾讯云服务器");
            }

            @Override
            public void onConnectSuccess() {
                L.e("连接成功");
            }

            @Override
            public void onConnectFailed(int code, String error) {
                L.e("连接失败");
            }

            @Override
            public void onKickedOffline() {
                L.e("被踢下线");
                SPUtils.getInstance().setIntegerValue(SPUtils.IM_LOGIN_STATUS, LOGIN_STATUS_OFFLINE);
            }

            @Override
            public void onUserSigExpired() {
                L.e("登录票据过期");
                //重新获取UserSig
                SPUtils.getInstance().setStringValue(SPUtils.IM_LOGIN, "");
            }

            @Override
            public void onSelfInfoUpdated(V2TIMUserFullInfo info) {
                L.e("当前用户资料发生更新");
            }
        });
    }

    /**
     * 登录：首次使用 IM、登录票据已过期、用户被踢下线
     *
     * @param uid      登录账号，建议只包含大小写英文字母（a-z、A-Z）、数字（0-9）、下划线（_）和连词符（-），长度最大不超过32字节。
     * @param callback
     */
    @Override
    public void login(String uid, CommonCallback<Boolean> callback) {
        V2TIMManager.getInstance().login(uid, GenerateTestUserSig.genTestUserSig(uid), new V2TIMCallback() {
            @Override
            public void onError(int code, String desc) {
                L.e("IM login error--code==" + code + "desc==" + desc);
                SPUtils.getInstance().setIntegerValue(SPUtils.IM_LOGIN_STATUS, LOGIN_STATUS_OFFLINE);
                Toast.makeText(MyApplication.sInstener, "IM login failure", Toast.LENGTH_SHORT).show();
                if (callback != null) {
                    callback.callback(false);
                }
            }

            @Override
            public void onSuccess() {
                L.e("IM login success");
                SPUtils.getInstance().setIntegerValue(SPUtils.IM_LOGIN_STATUS, LOGIN_STATUS_ONLINE);
                if (callback != null) {
                    callback.callback(true);
                }
            }
        });
    }

    /**
     * 登出：退出登录、如果切换账号
     */
    @Override
    public void logout() {
        V2TIMManager.getInstance().logout(new V2TIMCallback() {
            @Override
            public void onError(int code, String desc) {
                L.e("IM logout error code==" + code + "desc==" + desc);
            }

            @Override
            public void onSuccess() {
                L.e("IM logout success");
            }
        });
    }

    /**
     * 获取会话列表
     *
     * @param nextSeq  拉取起始位置
     * @param count    拉取个数
     * @param callback v2TIMConversationResult.isFinish 是否拉取完毕
     */
    @Override
    public void getConversationList(int nextSeq, int count, final CommonCallback<V2TIMConversationResult> callback) {
        V2TIMManager.getConversationManager().getConversationList(nextSeq, count, new V2TIMValueCallback<V2TIMConversationResult>() {
            @Override
            public void onError(int code, String desc) {
                L.e("Tencent IM get conversation list error code==" + code + "desc==" + desc);
                if (callback != null) {
                    callback.callback(null);
                }
            }

            @Override
            public void onSuccess(V2TIMConversationResult v2TIMConversationResult) {
                L.e("Tencent IM get conversation list success ");
                if (callback != null) {
                    callback.callback(v2TIMConversationResult);
                }
            }
        });
    }

    /**
     * 获取会话用户
     *
     * @return
     */
    @Override
    public String getConversationUid() {
        return null;
    }

    /**
     * 获取消息
     *
     * @param uid      对方uid
     * @param count    消息数目
     * @param lastMsg  起始消息，null为最新消息
     * @param callback
     */
    @Override
    public void getHistoryMessageList(String uid, int count, V2TIMMessage lastMsg, final CommonCallback<List<MessageBean>> callback) {
        V2TIMManager.getMessageManager().getC2CHistoryMessageList(uid, count, lastMsg, new V2TIMValueCallback<List<V2TIMMessage>>() {
            @Override
            public void onError(int code, String desc) {
                L.e("Tencent IM get history message error code==" + code + "descc==" + desc);
                callback.callback(null);
            }

            @Override
            public void onSuccess(List<V2TIMMessage> v2TIMMessages) {
                L.e("Tencent IM get history message success");
                Collections.reverse(v2TIMMessages);
                callback.callback(TIMMessageToBean(v2TIMMessages));
            }
        });
    }

    @Override
    public int getUnReadMsgCount(String uid) {
        return 0;
    }

    @Override
    public void markConversationAsRead(String uid, boolean needRefresh, final CommonCallback<Boolean> callback) {
        V2TIMManager.getMessageManager().markC2CMessageAsRead(uid, new V2TIMCallback() {
            @Override
            public void onError(int code, String desc) {
                L.e("Tencent IM mark message as read error code==" + code + "desc==" + desc);
                callback.callback(false);
            }

            @Override
            public void onSuccess() {
                L.e("Tencent IM mark message as read success");
                callback.callback(true);
            }
        });
    }

    @Override
    public int getAllUnReadMsgCount() {
        return 0;
    }

    @Override
    public void refreshAllUnReadMsg() {

    }

    @Override
    public MessageBean createTextMessage(String toUid, String text) {
        return null;
    }

    @Override
    public MessageBean createImageMessage(String toUid, String path) {
        return null;
    }

    /**
     * 消息监听
     */
    @Override
    public void setOnMessageListener(final CommonCallback<MessageBean> callback) {
        V2TIMManager.getInstance().addSimpleMsgListener(new V2TIMSimpleMsgListener() {
            @Override
            public void onRecvC2CTextMessage(String msgID, V2TIMUserInfo sender, String text) {
                super.onRecvC2CTextMessage(msgID, sender, text);
                L.e("Tencent IM message listener c2c text message text==" + text);
                MessageBean messageBean = new MessageBean(sender.getUserID(), sender.getNickName(), sender.getNickName(), sender.getFaceUrl(), 0, V2TIM_ELEM_TYPE_TEXT, text, "", null);
                callback.callback(messageBean);
            }

            @Override
            public void onRecvC2CCustomMessage(String msgID, V2TIMUserInfo sender, byte[] customData) {
                super.onRecvC2CCustomMessage(msgID, sender, customData);
                L.e("Tencent IM message listener c2c custom message");
                MessageBean messageBean = new MessageBean(sender.getUserID(), sender.getNickName(), sender.getNickName(), sender.getFaceUrl(), 0, V2TIM_ELEM_TYPE_CUSTOM, "", "", customData);
                callback.callback(messageBean);
            }
        });
    }

    /**
     * @param toUid 好友 Id
     * @param text  发送的文本消息，会经过敏感词过滤，包含的敏感词消息在发送时会报80001错误码。
     */
    @Override
    public void sendTextMessage(String toUid, String text, final SendMsgResultCallback callback) {

//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("extKey", "ext content");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        String extContent = jsonObject.toString();
//        V2TIMOfflinePushInfo v2TIMOfflinePushInfo = new V2TIMOfflinePushInfo();
//        v2TIMOfflinePushInfo.setExt(extContent.getBytes());

        V2TIMManager.getInstance().sendC2CTextMessage(text, toUid, new V2TIMSendCallback<V2TIMMessage>() {

            @Override
            public void onProgress(int progress) {

            }

            @Override
            public void onError(int code, String desc) {
                L.e(TAG, "tencent IM send text message error:code==" + code + "desc==" + desc);
                callback.sendFinish(false, null);
            }

            @Override
            public void onSuccess(V2TIMMessage v2TIMMessage) {
                L.e(TAG, "tencent IM send text message success");
                callback.sendFinish(true, v2TIMMessage);
            }
        });
    }

    /**
     * @param toUid
     * @param customMessage 二进制 buffer
     * @param callback
     */
    @Override
    public void sendCustomMessage(String toUid, String customMessage, final SendMsgResultCallback callback) {
        V2TIMManager.getInstance().sendC2CCustomMessage(customMessage.getBytes(), toUid, new V2TIMValueCallback<V2TIMMessage>() {
            @Override
            public void onError(int code, String desc) {
                L.e("tencent IM send custom message error:code==" + code + "desc==" + desc);
                callback.sendFinish(false, null);
            }

            @Override
            public void onSuccess(V2TIMMessage v2TIMMessage) {
                L.e("tencent IM send custom message success");
                callback.sendFinish(true, v2TIMMessage);
            }
        });
    }

    @Override
    public void sendModelMessage(String toUid, MessageBean messageBean, SendMsgResultCallback callback) {

    }

    @Override
    public void getUserInfo(String uIds, CommonCallback<List<UserInfoBean>> callback) {
        List<String> idList = Arrays.asList(uIds.split(","));
        V2TIMManager.getInstance().getUsersInfo(idList, new V2TIMValueCallback<List<V2TIMUserFullInfo>>() {
            @Override
            public void onError(int code, String desc) {
                L.e(TAG, "tencent IM get user info error code==" + code + " desc==" + desc);
                if (callback != null) {
                    callback.callback(null);
                }
            }

            @Override
            public void onSuccess(List<V2TIMUserFullInfo> v2TIMUserFullInfo) {
                L.e(TAG, "tencent IM get user info success");
                List<UserInfoBean> userInfoList = new ArrayList<>();
                if (callback != null) {
                    for (V2TIMUserFullInfo userInfo : v2TIMUserFullInfo) {
                        UserInfoBean bean = new UserInfoBean();
                        bean.setUid(userInfo.getUserID());
                        bean.setNickName(userInfo.getNickName());
                        bean.setFaceUrl(userInfo.getFaceUrl());
                        bean.setGender(userInfo.getGender());
                        bean.setSignature(userInfo.getSelfSignature());
                        userInfoList.add(bean);
                    }
                    callback.callback(userInfoList);
                }
            }
        });
    }

    public List<MessageBean> TIMMessageToBean(List<V2TIMMessage> v2TIMMessages) {
        List<MessageBean> messageBeanList = new ArrayList<>();
        for (V2TIMMessage v2TIMMessage : v2TIMMessages) {
            L.e("TencentImUtils--senderId==" + v2TIMMessage.getSender());
            switch (v2TIMMessage.getElemType()) {
                case V2TIM_ELEM_TYPE_TEXT:
                    messageBeanList.add(new MessageBean(v2TIMMessage.getSender(), v2TIMMessage.getFriendRemark(), v2TIMMessage.getNickName(), v2TIMMessage.getFaceUrl(), v2TIMMessage.getTimestamp(), v2TIMMessage.getElemType(), v2TIMMessage.getTextElem().getText(), "", new byte[]{}));
                    break;
                case V2TIM_ELEM_TYPE_CUSTOM:
                    messageBeanList.add(new MessageBean(v2TIMMessage.getSender(), v2TIMMessage.getFriendRemark(), v2TIMMessage.getNickName(), v2TIMMessage.getFaceUrl(), v2TIMMessage.getTimestamp(), v2TIMMessage.getElemType(), "", "", v2TIMMessage.getCustomElem().getData()));
                    break;
                case V2TIM_ELEM_TYPE_IMAGE:
                    messageBeanList.add(new MessageBean(v2TIMMessage.getSender(), v2TIMMessage.getFriendRemark(), v2TIMMessage.getNickName(), v2TIMMessage.getFaceUrl(), v2TIMMessage.getTimestamp(), v2TIMMessage.getElemType(), "", v2TIMMessage.getImageElem().getImageList().get(0).getUrl(), new byte[]{}));
                    break;
            }
        }
        return messageBeanList;
    }

    @Override
    public void setOfflinePush(long business, String uid, CommonCallback<Boolean> callback) {
        V2TIMOfflinePushConfig pushConfig = new V2TIMOfflinePushConfig(business, uid);
        V2TIMManager.getOfflinePushManager().setOfflinePushConfig(pushConfig, new V2TIMCallback() {
            @Override
            public void onError(int code, String desc) {
                L.e(TAG, "Tencent IM setOfflinePush error code==" + code + "desc==" + desc);
                if (callback != null) {
                    callback.callback(false);
                }
            }

            @Override
            public void onSuccess() {
                L.e(TAG, "Tencent IM setOfflinePush success");
                if (callback != null) {
                    callback.callback(true);
                }
            }
        });
    }
}
